#!/usr/bin/env node
const program = require('commander')

const optionTests = ['-t, --tests', 'set target to <root>/tests']

const requireWithENV = (modeEnv, modeTest, modeSsr) => {
  if (modeEnv) { process.env.MODE_ENV = modeEnv + '' }
  if (modeTest) { process.env.MODE_TEST = modeTest + '' }
  if (modeSsr) { process.env.MODE_SSR = modeSsr + '' }
  return args => {
    const m = require(args)
    return m && m.default ? m.default : m
  }
}

program
  .command('try [env]')
  .option(...optionTests)
  .action((env = '', options) => console.log(env, options))

program
  .command('buildservice')
  .alias('bs')
  .option(...optionTests)
  .description('build js and css in webpack dev server, default set ENV=hot')
  .action(options => requireWithENV('hot', options.tests, false)('./buildservice')())

program
  .command('build')
  .alias('b')
  .option(...optionTests)
  .description('build code from src/ to build/ as module in node_modules')
  .action(options => requireWithENV(null, options.tests, false)('./build')())

program
  .command('buildclient [env]')
  .alias('bc')
  .option(...optionTests)
  .description('build js and css files from src/ to buildclient/ by webpack with special ENV=env')
  .action((env, options) => requireWithENV(env, options.tests, false)('./buildclient')())

program
  .command('buildssr [env]')
  .alias('bs')
  .option(...optionTests)
  .description('run build and buildclient both with special ENV=env, then write ENV and PROJECT in build directory')
  .action((env, options) => requireWithENV(env, options.tests, true)('./buildssr')())

program
  .command('jest')
  .alias('j')
  .description('run unit tests of jest in tests/*.test.js files')
  .action(() => requireWithENV(null, null, false)('./jest')())

program
  .command('version')
  .alias('v')
  .description('show version of the command')
  .action(() => console.log(require('../../package.json').version))

program.parse(process.argv)
